import { execSync } from 'child_process';

import config from '#Config/database.js'

import { dataGet, empty } from '#Utils/helper.js';

import yargs from 'yargs';
(() => {

    const argv = yargs(process.argv.slice(2)).argv;
    console.log(argv);
    

    const dbConfigs = dataGet(config, "connections", {}), dbConnect = dataGet(config, "connect", 'koa');

    const method = dataGet(argv, 'method'), name = dataGet(argv, 'name', dbConnect);

    const dbConfig = dataGet(dbConfigs, dbConnect, {});
    let url = '';
    if (dbConfig.dialect == 'sqlite') {
        url = `${dbConfig.dialect}://${dbConfig.storage}`;
    }
    if (dbConfig.dialect == 'mysql') {
        url = `${dbConfig.dialect}://${dbConfig.username}:${dbConfig.password}@${dbConfig.host}/${dbConfig.database}`;
    }
    if (empty(url)) {
        throw new Error(`Database connection for ${dbConnect} established successfully.`)
    }

    console.log(url);

    if (method) {
        if (method === 'migrate') {
            execSync(`npx sequelize-cli db:migrate --url=${url}`);
        } else if (method === 'undo') {
            execSync(`npx sequelize-cli db:migrate:undo --url=${url}`);
        }
    } else {
        console.info('请指定方法');
    }


    // execSync(`npx sequelize-cli db:migrate --url=${url}`);
})()